//
//  TeavelTopicDetailsViewController.m
//  ToWhere
//
//  Created by dllo on 15/11/15.
//  Copyright © 2015年 www.TE.com. All rights reserved.
//

#import "TeavelTopicDetailsViewController.h"
#import "DataAnalysis.h"
#import "TravelTopicModel.h"
#import <SDWebImageManager.h>
#import <UIImageView+WebCache.h>
#import "TravelTopicDetailsOneTableViewCell.h"
#import "TravelTopicDetailsTwoTableViewCell.h"
#import "TravelTopicDetailsThreeTableViewCell.h"
#import "TravelTopicDeBtnTableViewCell.h"

#import "TravelTopicPicTableViewCell.h"

#import "TravetTourDetailsViewController.h"
#import "CoreDatamanager.h"
#import "ZTCollection.h"
#import "UMSocial.h"

@interface TeavelTopicDetailsViewController ()<UITableViewDataSource, UITableViewDelegate>

//接收网络请求
@property (nonatomic, retain) NSMutableArray *arrLoading;
//创建tableView
@property (nonatomic, retain) UITableView *tableView;

//头视图照片
@property (nonatomic, retain) UIImageView *imagePic;

//头视图name
@property (nonatomic, retain) UILabel *labelName;
//头视图title
@property (nonatomic, retain) UILabel *labelTitle;

@property (nonatomic, retain) TravelTopicModel *model;

@property (nonatomic, retain) UIView *titleView;

@property (nonatomic, assign) NSInteger num;


@property (nonatomic, copy) NSString* strI;

@property (nonatomic, retain) NSArray *array;

@property (nonatomic, retain) NSArray *coreArray;

@property (nonatomic, retain) NSArray *resultArray;

@property (nonatomic, retain) UILabel * titleLabel;

@property (nonatomic, retain) CoreDatamanager *coreDataManager;
@end

@implementation TeavelTopicDetailsViewController

-(void)dealloc
{
    [_arrLoading release];
    [_tableView release];
    [_imagePic release];
    [_labelName release];
    [_labelTitle release];
    [_idstring release];
    [_strI release];
    [_titleLabel release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.coreDataManager = [CoreDatamanager shareManager];
    NSLog(@"%@",[self.coreDataManager applicationDocumentsDirectory]);
    // Do any additional setup after loading the view.
    
    self.num = 0;
    self.arrLoading  = [NSMutableArray array];

    //创建tableView
    [self createTableView];
    //创建头视图
//    [self createHeaderView];
    [self createTitle];
    //网络请求
    [self loading];

    
    
    
}
#pragma mark 创建标题
-(void)createTitle
{
    
    
    self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,64)];
    self.titleView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    [self.view addSubview:self.titleView];
    [self.titleView release];
    [_titleView release];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(15 , 25 , 20 , 20 );
    [backBtn setBackgroundImage:[UIImage imageNamed:@"Food_back"] forState:UIControlStateNormal];
//    backBtn.backgroundColor = [UIColor blackColor];
    [self.titleView addSubview:backBtn];
    [backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
   self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 45 * kWidth, self.titleView.frame.size.height / 2 - 10 * kHeight, kWidth * 90, kHeight * 30)];
    
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
 
    [self.titleView addSubview:self.titleLabel];
    [_titleLabel release];
    


}
//分享等按钮的点击事件
-(void)btnAction:(UIButton *)btn
{
    if (btn.tag == 5000)
    {
       
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"ZTCollection"];
        self.resultArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
        if (self.resultArray.count == 0) {
             NSLog(@"收藏");
            ZTCollection *zt = [NSEntityDescription insertNewObjectForEntityForName:@"ZTCollection" inManagedObjectContext:_coreDataManager.managedObjectContext];
            zt.ztID = [NSString stringWithFormat:@"%@",self.idstring];
            zt.ztName = self.model.name;
            zt.ztUrl = self.model.image_url;
            [_coreDataManager saveContext];
            [btn setImage:[UIImage imageNamed:@"collected"] forState:UIControlStateNormal];
        }else{
            BOOL add = NO;
            int index = 0;
            for (int i = 0 ;i < self.resultArray.count; i++){
            
                if ([[self.resultArray[i] ztID] isEqualToString:[NSString stringWithFormat:@"%@",self.idstring]]) {
                    add = YES;
                    index = i;
                }
            
            }
            
            if (add) {
                 NSLog(@"取消收藏");
                [btn setImage:[UIImage imageNamed:@"collec"] forState:UIControlStateNormal];
                [_coreDataManager.managedObjectContext deleteObject:self.resultArray[index]];
                [_coreDataManager saveContext];
            }else{
                 NSLog(@"收藏");
                ZTCollection *zt = [NSEntityDescription insertNewObjectForEntityForName:@"ZTCollection" inManagedObjectContext:_coreDataManager.managedObjectContext];
                zt.ztID = [NSString stringWithFormat:@"%@",self.idstring];
                zt.ztName = self.model.name;
                zt.ztUrl = self.model.image_url;
                [_coreDataManager saveContext];
                [btn setImage:[UIImage imageNamed:@"collected"] forState:UIControlStateNormal];

            }
        
        }
    }
    else
    {
//        NSLog(@"分享");
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"5655ae58e0f55a464d000a1c"
                                          shareText:[NSString stringWithFormat:@"%@",self.idstring]
                                         shareImage:[UIImage imageNamed:@"icon.png"]
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                           delegate:nil];

    }
}





-(void)backAction:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
    
}

#pragma mark 网络请求
-(void)loading
{
    [DataAnalysis dataAnalysisGETWithUrlString:[NSString stringWithFormat:@"http://chanyouji.com/api/articles/%@.json?page=1", self.idstring] parameters:nil showHuD:YES hiddenView:nil successfulBlock:^(id responseObject) {
        
//        NSLog(@"%@", self.idstring);

        NSDictionary *dic = responseObject;

       self.model = [TravelTopicModel travelTopicModelinitWithNSDictionary:dic];
     
        //进行判断(是否被收藏)
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"ZTCollection"];
        self.coreArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
        BOOL result = NO;
        if (_coreArray.count > 0) {
            
            
            for (ZTCollection *ZT in self.coreArray) {
                if ([ZT.ztID isEqualToString:[NSString stringWithFormat:@"%@",self.idstring]]) {
                    result = YES;
                }
            }
            if (result == YES) {
                self.array = @[ @"collected", @"fenxiang"];
            }else{
                
                self.array = @[ @"collec", @"fenxiang"];
            }
            
            
        }else{
        
            self.array = @[ @"collec", @"fenxiang"];
        
        }
        for (int i = 0; i < 2; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(295 * kWidth + i * 40 , 25 , 20 * kWidth , 20 );
            [btn setBackgroundImage:[UIImage imageNamed:self.array[i]] forState:UIControlStateNormal];
            [self.view addSubview:btn];
            btn.tag = 5000 + i;
            [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
            
        }

        [self.tableView reloadData];
        
    } failureBlock:^(NSError *error) {
        
        NSLog(@"%@", error);
    }];
    
}


#pragma mark 创建tableView
-(void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -20 * kHeight - (1 - kHeight) * 20, self.view.frame.size.width, self.view.frame.size.height + 20 * kHeight + (1 - kHeight) * 20) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;    
    
    [self.tableView registerClass:[TravelTopicDetailsOneTableViewCell class] forCellReuseIdentifier:@"TravelTopicDetailsOneTableViewCell"];
    [self.tableView registerClass:[TravelTopicDetailsTwoTableViewCell class] forCellReuseIdentifier:@"TravelTopicDetailsTwoTableViewCell"];
    [self.tableView registerClass:[TravelTopicDetailsThreeTableViewCell class] forCellReuseIdentifier:@"TravelTopicDetailsThreeTableViewCell"];
    
    [self.tableView registerClass:[TravelTopicDeBtnTableViewCell class] forCellReuseIdentifier:@"TravelTopicDeBtnTableViewCell"];
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
    //self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.model.arr.count - 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
      
        CGFloat frame = [TravelTopicDetailsOneTableViewCell heightOfLabel:[self.model.arr[indexPath.row] DES] andTextFont:[UIFont systemFontOfSize:15 *kWidth] andTextWidth: 355 *kWidth];
        
        return frame + 20 *kHeight;
    }else if (indexPath.row == 1)
    {
        if ([[self.model.arr [indexPath. row] image_url] isEqualToString:@""]) {
            CGFloat frameTwo = [TravelTopicDetailsOneTableViewCell heightOfLabel:[self.model.arr[indexPath.row] DES] andTextFont:[UIFont systemFontOfSize:15 *kWidth] andTextWidth:365 *kWidth];
            return frameTwo + 40 *kHeight;
        }else{
        
            
            
            CGFloat frameThree = [TravelTopicDetailsOneTableViewCell heightOfLabel:[self.model.arr[indexPath.row] DES]
                                                                       andTextFont:[UIFont systemFontOfSize:15 *kWidth] andTextWidth:355 *kWidth];
            CGFloat wd = [[self.model.arr[indexPath.row] image_width] floatValue];
            CGFloat ht = [[self.model.arr[indexPath.row] image_height] floatValue];
            
            CGFloat www = (int)(frameThree + ht / wd *(self.view.frame.size.width - 10*kWidth)  + 25 * kHeight) ;
            if (www > 0) {
                return www;
            }else{
                return 0;
            }
            

        
        }
    }else{
        
        if ([[self.model.arr [indexPath.row] title] length] > 0) {
            CGFloat frameTwo = [TravelTopicDetailsOneTableViewCell heightOfLabel:[self.model.arr[indexPath.row] DES] andTextFont:[UIFont systemFontOfSize:15 *kWidth] andTextWidth:365 *kWidth];
            return frameTwo + 40 *kHeight;
            
        }else{

        self.strI = [self.model.arr [indexPath.row] DES];
        
        
        
        for (NSString *title in [[self.model.arr[indexPath.row]   description_user_ids] allKeys]) {
            if ([self.strI containsString:title]) {
                
                self.strI = [self.strI stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@ ",title] withString:[NSString stringWithFormat:@"%@ ",[[self.model.arr[indexPath.row] description_user_ids] objectForKey:title]]];
            }
            
        }

        
        
        
        CGFloat frameThree = [TravelTopicDetailsOneTableViewCell heightOfLabel:self.strI
                                                                   andTextFont:[UIFont systemFontOfSize:15 *kWidth] andTextWidth:355 *kWidth];
        CGFloat wd = [[self.model.arr[indexPath.row] image_width] floatValue];
        CGFloat ht = [[self.model.arr[indexPath.row] image_height] floatValue];
        
        NSString *strN = [[self.model.arr[indexPath.row] attraction] valueForKey:@"name"];
        
        if (strN.length != 0) {
            
               CGFloat ww = (int)(frameThree + ht / wd *(self.view.frame.size.width - 10*kWidth)  + 55 * kHeight) ;
            if (ww >0) {
                return ww;
            }else{
                return 0;
            }
        }
        
        
        CGFloat www = (int)(frameThree + ht / wd *(self.view.frame.size.width - 10*kWidth)  + 25 * kHeight) ;
        if (www > 0) {
            return www;
        }else{
            return 0;
        }
        }
        }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 200 * kHeight;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    self.imagePic = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200 *kHeight)];
    self.imagePic.backgroundColor = [UIColor redColor];

    
    [_imagePic release];
    
    self.labelName = [[UILabel alloc]initWithFrame:CGRectMake(0, self.imagePic.frame.size.height /  2 , self.imagePic.frame.size.width, 28 *kHeight)];
    self.labelName.textAlignment = NSTextAlignmentCenter;
    self.labelName.textColor = [UIColor whiteColor];
    [self.imagePic addSubview:self.labelName];
    [_labelName release];
    
    self.labelTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, self.labelName.frame.size.height + self.labelName.frame.origin.y  + 5*kHeight, self.labelName.frame.size.width, 28 *kHeight)];
    self.labelTitle.textAlignment = NSTextAlignmentCenter;
    self.labelTitle.textColor = [UIColor whiteColor];
    [self.imagePic addSubview:self.labelTitle];
    [_labelTitle release];
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(5 *kWidth, self.labelName.frame.size.height + self.labelName.frame.origin.y + 2 *kHeight, self.imagePic.frame.size.width / 2 - 15 *kWidth, 1 *kHeight)];
    leftView.backgroundColor = [UIColor whiteColor];
    [self.imagePic addSubview:leftView];
    [leftView release];
    
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(self.imagePic.frame.size.width / 2 + 10 * kWidth, leftView.frame.origin.y, leftView.frame.size.width, leftView.frame.size.height)];
    rightView.backgroundColor = [UIColor whiteColor];
    [self.imagePic addSubview:rightView];
    [rightView release];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(self.imagePic.frame.size.width / 2 - 2.5 *kWidth, leftView.frame.origin.y -2.5 *kHeight, 5 *kWidth, 5 *kWidth)];
    
    label.backgroundColor = [UIColor whiteColor];
    label.layer.masksToBounds = YES;
    label.layer.cornerRadius = 2.5;
    
    [self.imagePic addSubview:label];
    [label release];
    [self.imagePic sd_setImageWithURL:[NSURL URLWithString:self.model.image_url] placeholderImage:[UIImage imageNamed:@"Travel_place"]];
    self.labelName.text = self.model.name;
    self.labelTitle.text = self.model.title;

    
    return self.imagePic;
    
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0)
    {
        
        TravelTopicDetailsOneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TravelTopicDetailsOneTableViewCell" forIndexPath:indexPath];
        cell.model = self.model.arr[indexPath.row];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }else if (indexPath.row == 1)
    {
        if ([[self.model.arr[indexPath.row] image_url] isEqualToString:@""] )
        {
            
            TravelTopicDetailsTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TravelTopicDetailsTwoTableViewCell" forIndexPath:indexPath];
            cell.model = self.model.arr[indexPath.row];
         //   NSLog(@"%@", [self.model.arr[indexPath.row] DES]);
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        }else{
        
            TravelTopicDetailsThreeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TravelTopicDetailsThreeTableViewCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.model = self.model.arr[indexPath.row];
            return cell;

        }
        
    }else{
        
        /////////
        if ([[self.model.arr[indexPath.row] title] length] >0) {
            
            TravelTopicDetailsTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TravelTopicDetailsTwoTableViewCell" forIndexPath:indexPath];
            cell.model = self.model.arr[indexPath.row];
            //   NSLog(@"%@", [self.model.arr[indexPath.row] DES]);
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;

        }else{
        
        
        NSString *strName = [[self.model.arr[indexPath.row] attraction] valueForKey:@"name"];
        if (strName.length == 0) {
            TravelTopicDetailsThreeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TravelTopicDetailsThreeTableViewCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            cell.model = self.model.arr[indexPath.row];
            return cell;
        
        }else{
            
            TravelTopicDeBtnTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TravelTopicDeBtnTableViewCell" forIndexPath:indexPath];
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.model =self.model.arr[indexPath.row];
            cell.btnName.tag =(NSInteger)[[self.model.arr[indexPath.row] attraction] valueForKey:@"id"];
            [cell.btnName addTarget:self action:@selector(btnNameAction:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
            
        }
        
        }
        
    }
    
}

//////////////////////
-(void)btnNameAction:(UIButton *)sender
{
    TravetTourDetailsViewController *view = [[TravetTourDetailsViewController alloc]init];
    view.idNumber = (NSNumber *)sender.tag;
    [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:view animated:YES];
    
}



//当滚动时
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y > -45 && scrollView.contentOffset.y < 800) {
        self.titleView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:scrollView.contentOffset.y / 800];
    }
     self.titleLabel.text = @"专题详情";
    if (scrollView.contentOffset.y == -20  || scrollView.contentOffset.y <= -5) {
        self.titleLabel.hidden = YES;
    }else if (scrollView.contentOffset.y >30){
        self.titleLabel.hidden = NO;
    }
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
